<?php
/***************************************************************
*  Copyright notice
*  (c) 2009, jianyuzhu@gmail.com
*  All rights reserved
*  This script is part of the PPEMI project.
***************************************************************/

//
function func_attachment_post_convert($content, $attachments_ids) {
	//$content = preg_replace("/(\{\{local\}\})(\d+)(\{\{\/local\}\})/i", "{{attach}}\\2{{/attach}}", $content);
	/*
	for($i=0, $n=sizeof($attachments_ids); $i<$n; $i++) {
		if( $attachments_ids[$i] > 0 ) {
			$content = preg_replace("/(\{\{local\}\})" . ($i+1) . "(\{\{\/local\}\})/i", "{{attach}}" . $attachments_ids[$i] . "{{/attach}}", $content);
		} else {
			$content = preg_replace("/(\{\{local\}\})" . ($i+1) . "(\{\{\/local\}\})/i", "", $content);
		}
	}
	$content = preg_replace("/(\{\{local\}\})(\d+)(\{\{\/local\}\})/i", "", $content);
	*/
	for($i=0, $n=sizeof($attachments_ids); $i<$n; $i++) {
		if( $attachments_ids[$i] > 0 ) {
			$pattern[] = "/(\{\{local\}\})" . ($i+1) . "(\{\{\/local\}\})/i";
			$replacement[] = "{{attach}}" . $attachments_ids[$i] . "{{/attach}}";
		} else {
			$pattern[] = "/(\{\{local\}\})" . ($i+1) . "(\{\{\/local\}\})/i";
			$replacement[] = "";
		}
	}
	if( is_array($pattern) ) {
		$content = preg_replace($pattern, $replacement, $content);
		$content = preg_replace("/(\{\{local\}\})(\d+)(\{\{\/local\}\})/i", "", $content);
	}
	
	return $content;
}

function func_attachment_view_convert($content) {
	global $resObj;
	
	if( is_object($resObj) && get_class($resObj) == 'ResourceBase' ) {
		//
	} else {
		global $adb;
		include_once(CONFIG_PATH . CONFIG_DIR_CLASSES . 'core.resource.class.php');
		$resObj = new CoreResourceBase();
	}
	
	//
	if( preg_match_all("/\{\{attach\}\}(\d+)\{\{\/attach\}\}/i", $content, $matches) ) {
		//$attachments_pattern = $matches['0'];
		$attachments_ids = $matches['1'];
		
		$attachments_idstmp = array_unique($attachments_ids);
		$attachments_arrtmp = $resObj->getItemsValues(array('ids' => $attachments_idstmp));
		if( is_array($attachments_arrtmp) ) {
			for($i=0, $n=sizeof($attachments_arrtmp); $i<$n; $i++) {
				$attachments_arr[$attachments_arrtmp[$i]['resources_id']] = '<img class="attachimage" src="' . CONFIG_URL_HTTP . CONFIG_DIR_IMAGES . 'resources/' . $attachments_arrtmp[$i]['resources_value'] . '">';
			}
		}
		if( is_array($attachments_ids) ) {
			for($i=0, $n=sizeof($attachments_ids); $i<$n; $i++) {
				$attachments_pattern[] = "/(\{\{attach\}\})" . $attachments_ids[$i] . "(\{\{\/attach\}\})/";
				$attachments_replacement[] = $attachments_arr[$attachments_ids[$i]];
			}
		}
		$content = preg_replace($attachments_pattern, $attachments_replacement, $content);
	}
	
	return $content;
}
//
?>